<template>
  <div class="wms-app">
    <!-- 移库类型选择页面 -->
    <div v-if="currentView === 'transfer-types'" class="transfer-types">
      <div class="header">
        <h1>移库管理</h1>
      </div>
      
      <div class="transfer-type-grid">
        <div 
          class="transfer-type-card"
          @click="selectTransferType('normal')"
        >
          <div class="type-icon">📦</div>
          <div class="type-name">普通移库</div>
          <div class="type-desc">库位间商品移动</div>
        </div>
        
        <div 
          class="transfer-type-card"
          @click="selectTransferType('good-to-bad')"
        >
          <div class="type-icon">⚠️</div>
          <div class="type-name">良品转残</div>
          <div class="type-desc">移入 CP-01-01-01-01</div>
        </div>
        
        <div 
          class="transfer-type-card"
          @click="selectTransferType('bad-to-good')"
        >
          <div class="type-icon">✅</div>
          <div class="type-name">残品转良</div>
          <div class="type-desc">从 CP-01-01-01-01 移出</div>
        </div>
        
        <div 
          class="transfer-type-card"
          @click="currentView = 'transfer-list'"
        >
          <div class="type-icon">📄</div>
          <div class="type-name">移库单数据</div>
          <div class="type-desc">查看和管理移库单</div>
        </div>
      </div>
    </div>

    <!-- 移库单创建页面 -->
    <div v-if="currentView === 'create-transfer'" class="create-transfer">
      <div class="header">
        <button class="back-btn" @click="backToTransferTypes">← 返回</button>
        <h2>{{ getTransferTypeName() }}</h2>
      </div>
      
      <div class="transfer-form">
        <!-- 移库单号 - 隐藏但保留数据 -->
        <div class="form-section" style="display: none;">
          <div class="section-title">移库单信息</div>
          <div class="form-group">
            <label>移库单号:</label>
            <input 
              v-model="transferForm.transferNumber" 
              type="text" 
              placeholder="系统自动生成"
              disabled
            >
          </div>
        </div>

        <!-- 商品信息 -->
        <div class="form-section compact-section">
          
          <!-- 库位编码输入 -->
          <div class="form-group inline-input">
            <label class="inline-label">库位:</label>
            <input 
              v-model="locationSearchQuery"
              type="text" 
              placeholder="请输入库位编码（如：A01-01-01-01）"
              @keyup.enter="performSmartSearch"
              class="search-input mobile-narrow inline-input-field"
              style="font-family: monospace;"
            >
          </div>
          
          <!-- 商品条码输入 -->
          <div class="form-group inline-input">
            <label class="inline-label">条码:</label>
            <input 
              v-model="barcodeSearchQuery"
              type="text" 
              placeholder="请输入商品条码"
              @keyup.enter="performSmartSearch"
              class="search-input mobile-narrow inline-input-field"
            >
          </div>
          
          <!-- 搜索按钮 -->
          <div class="form-group">
            <button 
              @click="performSmartSearch" 
              class="smart-search-btn"
              :disabled="!hasSearchInput"
            >
              <span class="search-icon">🔍</span>
              <span class="search-text">{{ getSearchButtonText() }}</span>
            </button>
          </div>
          
          <!-- 搜索结果 -->
          <div v-if="searchResults.length > 0" class="search-results">
            <div class="results-header">搜索结果 ({{ searchResults.length }}条)</div>
            <div class="results-list">
              <div 
                v-for="(result, index) in searchResults" 
                :key="index"
                class="result-item"
                :class="{ selected: selectedProduct && selectedProduct.id === result.id }"
                @click="selectProduct(result)"
              >
                <div class="result-main">
                  <div class="product-name">{{ result.productName }}</div>
                  <div class="product-info-grid">
                    <div class="info-item">
                      <span class="info-label">条码:</span>
                      <span class="info-value barcode">{{ result.barcode || '无' }}</span>
                    </div>
                    <div class="info-item">
                      <span class="info-label">库位:</span>
                      <span class="info-value location">{{ result.locationCode }}</span>
                    </div>
                    <div class="info-item">
                      <span class="info-label">可用:</span>
                      <span class="info-value stock">{{ result.availableStock || result.lockedStock }}件</span>
                    </div>
                    <div class="info-item">
                      <span class="info-label">库位库存:</span>
                      <span class="info-value total-stock">{{ result['689edaf7a92ea0c35cc9c8d7'] || result.stockQuantity }}件</span>
                    </div>
                    <div class="info-item">
                      <span class="info-label">供应商:</span>
                      <span class="info-value supplier">{{ result.supplierName || '无' }}</span>
                    </div>
                    <div v-if="result.productionDate" class="info-item">
                      <span class="info-label">生产日期:</span>
                      <span class="info-value production-date">{{ formatDate(result.productionDate) }}</span>
                    </div>
                  </div>
                  <!-- 库存状态指示器 - 隐藏 -->
                  <div v-if="false" class="stock-status">
                    <span 
                      class="status-indicator" 
                      :class="getStockStatusClass(result)"
                      :title="getStockStatusText(result)"
                    >
                      {{ getStockStatusText(result) }}
                    </span>
                  </div>
                </div>
                <div class="select-indicator">
                  <span v-if="selectedProduct && selectedProduct.id === result.id">✓</span>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 已选择的商品显示 - 隐藏 -->
          <div v-if="false && selectedProduct" class="selected-product">
            <div class="selected-header">已选择商品</div>
            <div class="selected-info">
              <div class="selected-name">{{ selectedProduct.productName }}</div>
              <div class="selected-details">
                <span>库位: {{ selectedProduct.locationCode }}</span>
                <span>库存: {{ selectedProduct.availableStock || selectedProduct.lockedStock }}件</span> <!-- ✅ 优先显示可用库存 -->
                <span>供应商: {{ selectedProduct.supplierName || '无' }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 库位信息和移库数量 -->
        <div class="form-section compact-section">
          
          <!-- 普通移库显示移出和移入库位 -->
          <div v-if="selectedTransferType === 'normal'">
            <div v-if="false" class="form-group">
              <label>移出库位:</label>
              <input 
                :value="selectedProduct ? selectedProduct.locationCode : ''"
                type="text" 
                placeholder="请先选择商品"
                disabled
                class="auto-filled"
              >
            </div>
            <div class="form-group inline-input">
              <label class="inline-label">移至:</label>
              <input 
                v-model="transferForm.toLocationCode" 
                type="text" 
                placeholder="请输入移入库位编码"
                :class="{ 'error': locationError }"
                style="font-family: monospace;"
                title="库位编码需精准匹配，区分大小写"
                class="inline-input-field"
              >
              <div v-if="locationError" class="error-message">
                {{ locationError }}
              </div>
            </div>
          </div>
          
          <!-- 良品转残只显示移出库位 -->
          <div v-if="selectedTransferType === 'good-to-bad'">
            <div v-if="false" class="form-group">
              <label>移出库位:</label>
              <input 
                :value="selectedProduct ? selectedProduct.locationCode : ''"
                type="text" 
                placeholder="请先选择商品"
                disabled
                class="auto-filled"
              >
            </div>
            <div class="form-group inline-input">
              <label class="inline-label">移至:</label>
              <input 
                value="CP-01-01-01-01" 
                type="text" 
                disabled
                class="fixed-location inline-input-field"
              >
            </div>
          </div>
          
          <!-- 残品转良只显示移入库位 -->
          <div v-if="selectedTransferType === 'bad-to-good'">
            <div v-if="false" class="form-group">
              <label>移出库位:</label>
              <input 
                value="CP-01-01-01-01" 
                type="text" 
                disabled
                class="fixed-location"
              >
            </div>
            <div class="form-group inline-input">
              <label class="inline-label">移至:</label>
              <input 
                v-model="transferForm.toLocationCode" 
                type="text" 
                placeholder="请输入移入库位编码"
                :class="{ 'error': locationError }"
                style="font-family: monospace;"
                title="库位编码需精准匹配，区分大小写"
                class="inline-input-field"
              >
              <div v-if="locationError" class="error-message">
                {{ locationError }}
              </div>
            </div>
          </div>
          
          <!-- 移库数量信息 -->
          <div v-if="false" class="form-group inline-input">
            <label class="inline-label">库存:</label>
            <span class="stock-info inline-display">{{ availableStock }} 件</span>
          </div>
          <div class="form-group inline-input">
            <label class="inline-label">数量:</label>
            <input 
              v-model="transferForm.quantity" 
              type="number" 
              placeholder="请输入移库数量"
              min="1"
              :max="availableStock"
              @input="validateQuantity"
              :class="{ 'error': quantityError }"
              class="inline-input-field"
            >
            <div v-if="quantityError" class="error-message">
              {{ quantityError }}
            </div>
          </div>
        </div>

        <!-- 提交按钮 -->
        <div class="form-actions">
          <button 
            class="submit-btn go-transfer-btn" 
            @click="showSubmitConfirm"
            :disabled="!canSubmit"
          >
            去移库
          </button>
          
        </div>
      </div>
    </div>

    <!-- 移库单列表页面 -->
    <div v-if="currentView === 'transfer-list'" class="transfer-list">
      <div class="header">
        <button class="back-btn" @click="backToTransferTypes">← 返回</button>
        <h2>移库单列表</h2>
        <button class="add-btn" @click="currentView = 'transfer-types'">+ 新建</button>
      </div>
      
      <div class="transfer-items">
        <div v-if="transferOrders.length === 0" class="empty-state">
          <div class="empty-icon">📄</div>
          <div class="empty-text">暂无移库单</div>
          <button class="create-btn" @click="currentView = 'transfer-types'">创建第一个移库单</button>
        </div>
        
        <div 
          v-for="transfer in transferOrders" 
          :key="transfer.id"
          class="transfer-item"
        >
          <div class="transfer-info">
            <div class="transfer-number">{{ transfer.transferNumber }}</div>
            <div class="transfer-meta">
              <div class="meta-item">
                <span class="meta-label">商品名称:</span>
                <span class="meta-value">{{ transfer.productName || '未知商品' }}</span>
              </div>
              <div class="meta-item">
                <span class="meta-label">移库类型:</span>
                <span class="meta-value">{{ getTransferTypeName(transfer.transferType) }}</span>
              </div>
              <div class="meta-item">
                <span class="meta-label">移出库位:</span>
                <span class="meta-value">{{ transfer.fromLocationCode || '未知' }}</span>
              </div>
              <div class="meta-item">
                <span class="meta-label">移入库位:</span>
                <span class="meta-value">{{ transfer.toLocationCode || '未知' }}</span>
              </div>
              <div class="meta-item">
                <span class="meta-label">移库数量:</span>
                <span class="meta-value">{{ transfer.quantity || 0 }} 件</span>
              </div>
              <div class="meta-item">
                <span class="meta-label">创建时间:</span>
                <span class="meta-value">{{ formatDateTime(transfer.createTime) }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 确认弹窗 -->
    <div v-if="showConfirmModal" class="modal-overlay" @click="closeModal">
      <div class="modal-content" @click.stop>
        <h3>{{ confirmTitle }}</h3>
        <p>{{ confirmMessage }}</p>
        <div class="modal-actions">
          <button class="cancel-btn" @click="closeModal">取消</button>
          <button class="confirm-btn" @click="confirmAction">确认</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import transferApi from './api/transfer-new.js';

// 读取运行时 webhookUrl（与 YK.md 变量ID一致）
function getEnvRoot() {
  try {
    if (typeof window !== 'undefined') {
      if (window.mdye && window.mdye.env && window.mdye.env.config) return window.mdye.env.config
      if (window.parent && window.parent !== window && window.parent.mdye && window.parent.mdye.env && window.parent.mdye.env.config) return window.parent.mdye.env.config
      if (window.top && window.top !== window && window.top.mdye && window.top.mdye.env && window.top.mdye.env.config) return window.top.mdye.env.config
    }
  } catch (e) {}
  return {}
}
const MINGDAO_CONFIG = getEnvRoot()

// 页面状态
const currentView = ref('transfer-types');
const selectedTransferType = ref('');
const showConfirmModal = ref(false);
const confirmTitle = ref('');
const confirmMessage = ref('');
const confirmType = ref('');
const confirmData = ref(null); // 存储确认时的数据快照
const loading = ref(false);
const quantityError = ref('');
const locationError = ref(''); // ✅ 新增库位验证错误状态

// 搜索相关状态
const locationSearchQuery = ref(''); // 库位编码搜索
const barcodeSearchQuery = ref(''); // 商品条码搜索
const searchResults = ref([]);
const selectedProduct = ref(null);
const searchTimeout = ref(null);
const currentSearchType = ref(''); // 当前搜索类型：'location', 'barcode', 'combined'

// 计算属性：检查是否有搜索输入
const hasSearchInput = computed(() => {
  return locationSearchQuery.value.trim() !== '' || barcodeSearchQuery.value.trim() !== ''
})

// 获取搜索按钮文本
function getSearchButtonText() {
  return '搜索'
}

// 获取搜索预览文本
function getSearchPreview() {
  const hasLocation = locationSearchQuery.value.trim() !== ''
  const hasBarcode = barcodeSearchQuery.value.trim() !== ''
  
  if (hasLocation && hasBarcode) {
    return `将搜索库位"${locationSearchQuery.value}"和条码"${barcodeSearchQuery.value}"的匹配商品`
  } else if (hasLocation) {
    return `将搜索库位"${locationSearchQuery.value}"中的所有商品`
  } else if (hasBarcode) {
    return `将搜索条码"${barcodeSearchQuery.value}"对应的商品`
  } else {
    return '请输入库位编码或商品条码进行搜索'
  }
}

// 智能搜索函数
async function performSmartSearch() {
  const hasLocation = locationSearchQuery.value.trim() !== ''
  const hasBarcode = barcodeSearchQuery.value.trim() !== ''
  
  if (!hasLocation && !hasBarcode) {
    alert('请输入库位编码或商品条码进行搜索')
    return
  }
  
  try {
    loading.value = true
    
    if (hasLocation && hasBarcode) {
      // 组合搜索
      await searchCombined()
    } else if (hasLocation) {
      // 库位搜索
      await searchByLocation()
    } else if (hasBarcode) {
      // 条码搜索  
      await searchByBarcode()
    }
  } catch (error) {
    console.error('智能搜索失败:', error)
    alert('搜索失败，请重试')
  } finally {
    loading.value = false
  }
}

// 表单数据
const transferForm = ref({
  transferNumber: '',
  productName: '',
  fromLocation: null,
  toLocationCode: '',
  quantity: '',
});

// 数据列表
const availableProducts = ref([]);
const availableFromLocations = ref([]);
const transferOrders = ref([]);

// 计算属性
const availableStock = computed(() => {
  console.log(`🔍 计算可用库存:`, {
    移库类型: selectedTransferType.value,
    选中商品: selectedProduct.value ? {
      名称: selectedProduct.value.productName,
      库位: selectedProduct.value.locationCode,
      availableStock字段: selectedProduct.value.availableStock,
      lockedStock字段: selectedProduct.value.lockedStock,
      stockQuantity字段: selectedProduct.value.stockQuantity
    } : null
  });
  
  if (!selectedProduct.value) {
    console.warn('⚠️ 未选择商品，可用库存为0');
    return 0;
  }
  
  // 优先使用 availableStock，然后是 stockQuantity，最后是 lockedStock
  const stock = selectedProduct.value.availableStock || 
                selectedProduct.value.stockQuantity || 
                selectedProduct.value.lockedStock || 0;
  
  console.log(`📊 计算结果: 可用库存 = ${stock}`);
  return stock;
});

const canSubmit = computed(() => {
  const hasProduct = selectedProduct.value !== null;
  const hasQuantity = transferForm.value.quantity > 0;
  const hasValidLocations = (() => {
    if (selectedTransferType.value === 'normal') {
      return selectedProduct.value && transferForm.value.toLocationCode.trim() !== '';
    } else if (selectedTransferType.value === 'good-to-bad') {
      return selectedProduct.value;
    } else if (selectedTransferType.value === 'bad-to-good') {
      return transferForm.value.toLocationCode.trim() !== '';
    }
    return false;
  })();
  
  // ✅ 新增：检查库位验证错误
  return hasProduct && hasQuantity && hasValidLocations && !quantityError.value && !locationError.value;
});

// 立即挂载调试函数到全局（延迟执行避免引用错误）
if (typeof window !== 'undefined') {
  // 立即挂载，确保控制台可以马上使用
  window.exposeDebugFunctions = () => {
    // 延迟获取函数引用，确保函数已经定义
    if (typeof checkRuntimeConfig !== 'undefined') window.checkRuntimeConfig = checkRuntimeConfig;
    if (typeof testApiInit !== 'undefined') window.testApiInit = testApiInit;
    if (typeof testLocationConnection !== 'undefined') window.testLocationConnection = testLocationConnection;
    if (typeof testLocationValidation !== 'undefined') window.testLocationValidation = testLocationValidation;
    if (typeof detectLocationField !== 'undefined') window.detectLocationField = detectLocationField;
    if (typeof testTransferWorksheetConnection !== 'undefined') window.testTransferWorksheetConnection = testTransferWorksheetConnection;
    if (typeof validateTransferFieldMapping !== 'undefined') window.validateTransferFieldMapping = validateTransferFieldMapping;
    if (typeof testFieldMapping !== 'undefined') window.testFieldMapping = testFieldMapping;
    
    console.log('🔧 调试函数已挂载到window对象，可以使用:');
    console.log('- checkRuntimeConfig() - 检查运行时配置');
    console.log('- testApiInit() - 测试API初始化');
    console.log('- testLocationConnection() - 测试库位管理表连接');
    console.log('- testLocationValidation() - 测试库位验证');
  };
}

// 页面加载
onMounted(async () => {
  console.log('移库管理系统初始化');
  // 确保运行时配置已读取
  transferApi.init();
  generateTransferNumber();
  await loadAvailableProducts();
  await loadTransferOrders();
  
  // 挂载调试函数到全局 - 使用新的方式
  if (window.exposeDebugFunctions) {
    window.exposeDebugFunctions();
  }
});

// 生成移库单号
function generateTransferNumber() {
  transferForm.value.transferNumber = transferApi.generateTransferNumber();
}

// 选择移库类型
function selectTransferType(type) {
  selectedTransferType.value = type;
  currentView.value = 'create-transfer';
  resetForm();
  
  // 根据类型设置默认库位
  if (type === 'good-to-bad') {
    transferForm.value.toLocationCode = 'CP-01-01-01-01';
  }
  // 注意：bad-to-good类型的fromLocation将在选择商品时自动设置
}

// 获取移库类型名称
function getTransferTypeName(type) {
  return transferApi.getTransferTypeName(type || selectedTransferType.value);
}

// 重置表单
function resetForm() {
  transferForm.value = {
    transferNumber: transferForm.value.transferNumber, // 保留单号
    productName: '',
    fromLocation: '',
    toLocationCode: '',
    quantity: '',
  };
  quantityError.value = '';
  locationError.value = ''; // ✅ 重置库位验证错误
  availableFromLocations.value = [];
  
  // 重置搜索相关状态
  locationSearchQuery.value = '';
  barcodeSearchQuery.value = '';
  searchResults.value = [];
  selectedProduct.value = null;
  currentSearchType.value = '';
}

// 返回移库类型选择
function backToTransferTypes() {
  currentView.value = 'transfer-types';
  selectedTransferType.value = '';
  resetForm();
}

// 加载可用商品
async function loadAvailableProducts() {
  try {
    loading.value = true;
    availableProducts.value = await transferApi.getAvailableProducts();
    console.log(`加载了 ${availableProducts.value.length} 个商品`);
  } catch (error) {
    console.error('加载商品列表失败:', error);
    alert('加载商品列表失败，请刷新重试');
  } finally {
    loading.value = false;
  }
}

// 加载移库单列表
async function loadTransferOrders() {
  try {
    const orders = await transferApi.getTransferOrders();
    transferOrders.value = orders.map(order => ({
      ...order,
      typeName: transferApi.getTransferTypeName(order.transferType),
      statusName: transferApi.getStatusName(order.status)
    }));
    console.log(`加载了 ${transferOrders.value.length} 个移库单`);
  } catch (error) {
    console.error('加载移库单列表失败:', error);
  }
}

// 移除了自动检测功能，现在使用独立的搜索框

// 按库位编码搜索
async function searchByLocation() {
  const query = locationSearchQuery.value.trim();
  if (!query) {
    searchResults.value = [];
    return;
  }
  
  try {
    loading.value = true;
    currentSearchType.value = 'location';
    console.log(`按库位编码搜索: ${query}`);
    
    searchResults.value = await transferApi.searchByLocationCode(query, selectedTransferType.value);
    console.log(`库位搜索结果: ${searchResults.value.length} 条`);
  } catch (error) {
    console.error('库位搜索失败:', error);
    searchResults.value = [];
  } finally {
    loading.value = false;
  }
}

// 按商品条码搜索
async function searchByBarcode() {
  const query = barcodeSearchQuery.value.trim();
  if (!query) {
    searchResults.value = [];
    return;
  }
  
  try {
    loading.value = true;
    currentSearchType.value = 'barcode';
    console.log(`按商品条码搜索: ${query}`);
    
    searchResults.value = await transferApi.searchByBarcode(query, selectedTransferType.value);
    console.log(`条码搜索结果: ${searchResults.value.length} 条`);
  } catch (error) {
    console.error('条码搜索失败:', error);
    searchResults.value = [];
  } finally {
    loading.value = false;
  }
}

// 组合搜索（库位 + 条码）
async function searchCombined() {
  const locationQuery = locationSearchQuery.value.trim();
  const barcodeQuery = barcodeSearchQuery.value.trim();
  
  if (!locationQuery || !barcodeQuery) {
    alert('请同时输入库位编码和商品条码进行组合搜索');
    return;
  }
  
  try {
    loading.value = true;
    currentSearchType.value = 'combined';
    console.log(`组合搜索: 库位=${locationQuery}, 条码=${barcodeQuery}`);
    
    // 同时执行两种搜索
    const [locationResults, barcodeResults] = await Promise.all([
      transferApi.searchByLocationCode(locationQuery, selectedTransferType.value).catch(() => []),
      transferApi.searchByBarcode(barcodeQuery, selectedTransferType.value).catch(() => [])
    ]);
    
    // 找到同时符合两个条件的商品
    const combinedResults = locationResults.filter(locationItem => {
      return barcodeResults.some(barcodeItem => 
        locationItem.id === barcodeItem.id && 
        locationItem.locationCode === locationQuery &&
        (locationItem.barcode === barcodeQuery || locationItem.productName.includes(barcodeQuery))
      );
    });
    
    searchResults.value = combinedResults;
    console.log(`组合搜索结果: ${combinedResults.length} 条精确匹配`);
    
    if (combinedResults.length === 0) {
      alert(`未找到同时匹配库位 "${locationQuery}" 和条码 "${barcodeQuery}" 的商品\n\n单独搜索结果:\n- 库位匹配: ${locationResults.length} 条\n- 条码匹配: ${barcodeResults.length} 条`);
    }
  } catch (error) {
    console.error('组合搜索失败:', error);
    searchResults.value = [];
  } finally {
    loading.value = false;
  }
}

// 兼容性函数
async function performSearch() {
  // 现在使用智能搜索
  await performSmartSearch();
}

// 选择商品
async function selectProduct(product) {
  console.log('🔍 选择商品开始:', {
    商品: product,
    移库类型: selectedTransferType.value,
    当前表单fromLocation: transferForm.value.fromLocation
  });
  
  console.log('🔍 选择商品详细数据检查:', {
    'product完整对象': product,
    'product.supplierName': product.supplierName,
    'product.productionDate': product.productionDate,
    'product所有字段': Object.keys(product)
  });
  
  selectedProduct.value = product;
  transferForm.value.productName = product.productName;
  
  // 根据移库类型设置fromLocation
  if (selectedTransferType.value === 'normal' || selectedTransferType.value === 'good-to-bad') {
    // ✅ 修复：当API返回的locationCode为空时，使用搜索时的库位编码
    let actualLocationCode = product.locationCode;
    if (!actualLocationCode || actualLocationCode.trim() === '') {
      // 如果API返回的locationCode为空，使用当前搜索的库位编码
      if (currentSearchType.value === 'location' && locationSearchQuery.value.trim()) {
        actualLocationCode = locationSearchQuery.value.trim();
        console.log(`🔧 API返回locationCode为空，使用搜索库位: "${actualLocationCode}"`);
      }
    }
    
    const newFromLocation = {
      id: product.id,
      locationCode: actualLocationCode,
      lockedStock: product.lockedStock,
      supplierName: product.supplierName,
      productionDate: product.productionDate
    };
    transferForm.value.fromLocation = newFromLocation;
    console.log('✅ 设置普通移库fromLocation:', newFromLocation);
  } else if (selectedTransferType.value === 'bad-to-good') {
    // 残品转良时，自动设置从CP-01-01-01-01移出
    const newFromLocation = {
      id: product.id,
      locationCode: 'CP-01-01-01-01',
      lockedStock: product.lockedStock,
      supplierName: product.supplierName,
      productionDate: product.productionDate
    };
    transferForm.value.fromLocation = newFromLocation;
    console.log('✅ 设置残品转良fromLocation:', newFromLocation);
  }
  
  // 清空数量和错误信息
  transferForm.value.quantity = '';
  quantityError.value = '';
  
  // 使用nextTick确保数据更新完成后再检查
  await nextTick();
  
  console.log('🔍 nextTick后的表单状态:', {
    fromLocation: transferForm.value.fromLocation,
    fromLocationLocationCode: transferForm.value.fromLocation?.locationCode,
    整个表单: transferForm.value
  });
  
  // ✅ 新增：选择商品后重新验证库位（针对普通移库）
  if (selectedTransferType.value === 'normal' && transferForm.value.toLocationCode?.trim()) {
    setTimeout(() => validateToLocation(), 100); // 延迟验证，确保数据更新完成
  }
}

// 验证数量
function validateQuantity() {
  const quantity = parseInt(transferForm.value.quantity);
  const maxStock = availableStock.value;
  
  console.log(`📊 数量验证检查:`, {
    输入数量: transferForm.value.quantity,
    解析数量: quantity,
    可用库存: maxStock,
    商品信息: selectedProduct.value ? {
      名称: selectedProduct.value.productName,
      库位: selectedProduct.value.locationCode,
      可用库存: selectedProduct.value.availableStock,
      锁定库存: selectedProduct.value.lockedStock,
      总库存: selectedProduct.value.stockQuantity
    } : null
  });
  
  quantityError.value = '';
  
  if (isNaN(quantity) || quantity <= 0) {
    quantityError.value = '请输入有效的数量';
    console.warn('❌ 数量验证失败: 无效数量');
    return;
  }
  
  if (quantity > maxStock) {
    quantityError.value = `数量不能超过可用库存 ${maxStock} 件`;
    console.warn(`❌ 数量验证失败: ${quantity} > ${maxStock}`);
    return;
  }
  
  console.log(`✅ 数量验证通过: ${quantity} <= ${maxStock}`);
}

// ✅ 新增：实时验证移入库位
async function validateToLocation() {
  const toLocationCode = transferForm.value.toLocationCode?.trim();
  
  console.log(`🔍 开始验证移入库位: "${toLocationCode}"`);
  
  locationError.value = '';
  
  // 基本验证
  if (!toLocationCode) {
    console.log('⚠️ 移入库位为空，跳过验证');
    return;
  }
  
  try {
    // 检查是否与移出库位相同（普通移库）
    if (selectedTransferType.value === 'normal' && selectedProduct.value) {
      const fromLocationCode = selectedProduct.value.locationCode?.trim();
      if (fromLocationCode === toLocationCode) {
        locationError.value = '移入库位不能与移出库位相同';
        console.warn(`❌ 库位验证失败: 移入库位 "${toLocationCode}" 与移出库位相同`);
        return;
      }
    }
    
    // 检查残品转良不能移入残品库位
    if (selectedTransferType.value === 'bad-to-good' && toLocationCode === 'CP-01-01-01-01') {
      locationError.value = '残品转良的移入库位不能是残品库位';
      console.warn(`❌ 库位验证失败: 残品转良不能移入残品库位`);
      return;
    }
    
    // 验证库位是否存在于库位管理表
    console.log(`🔍 实时验证库位 "${toLocationCode}" 是否存在于库位管理表`);
    const locationExists = await transferApi.validateLocationExists(toLocationCode);
    
    if (!locationExists) {
      locationError.value = `库位编码 "${toLocationCode}" 不存在，请检查输入是否正确`;
      console.warn(`❌ 实时库位验证失败: 库位 "${toLocationCode}" 不存在`);
      return;
    }
    
    console.log(`✅ 实时库位验证通过: "${toLocationCode}"`);
    
  } catch (error) {
    console.error('❌ 实时库位验证过程中发生错误:', error);
    // 实时验证失败时给出友好提示，但不阻止用户继续输入
    locationError.value = `无法验证库位：${error.message}`;
    console.warn('⚠️ 实时验证失败，将在提交时再次验证');
  }
}

// ✅ 新增：库位输入变化时的防抖验证
let locationValidationTimeout = null;
function onLocationInput() {
  // 清除之前的验证错误
  locationError.value = '';
  
  // 防抖处理
  if (locationValidationTimeout) {
    clearTimeout(locationValidationTimeout);
  }
  
  locationValidationTimeout = setTimeout(() => {
    validateToLocation();
  }, 500); // 500ms 防抖
}

// 显示提交确认
function showSubmitConfirm() {
  const form = transferForm.value;
  const typeName = getTransferTypeName();
  
  console.log('🔍 showSubmitConfirm - 表单数据检查:', {
    transferType: selectedTransferType.value,
    formToLocationCode: form.toLocationCode,
    formFromLocation: form.fromLocation,
    formQuantity: form.quantity,
    productName: form.productName
  });
  
  let fromLocation, toLocation;
  
  if (selectedTransferType.value === 'normal') {
    fromLocation = form.fromLocation.locationCode;
    toLocation = form.toLocationCode;
  } else if (selectedTransferType.value === 'good-to-bad') {
    fromLocation = form.fromLocation.locationCode;
    toLocation = 'CP-01-01-01-01';
  } else if (selectedTransferType.value === 'bad-to-good') {
    fromLocation = 'CP-01-01-01-01';
    toLocation = form.toLocationCode;
  }
  
  confirmTitle.value = '确认创建移库单';
  confirmMessage.value = `${typeName}\n商品：${form.productName}\n从 ${fromLocation} 移至 ${toLocation}\n数量：${form.quantity} 件`;
  confirmType.value = 'submit';
  
  // 保存数据快照，防止异步操作中数据丢失
  confirmData.value = {
    transferType: selectedTransferType.value,
    productName: form.productName,
    quantity: form.quantity,
    toLocationCode: form.toLocationCode,
    fromLocation: form.fromLocation,
    transferNumber: form.transferNumber,
    selectedProduct: { ...selectedProduct.value } // 深拷贝选中的商品数据
  };
  
  console.log('💾 保存确认数据快照:', confirmData.value);
  
  showConfirmModal.value = true;
}

// 确认操作
async function confirmAction() {
  if (confirmType.value === 'submit') {
    try {
      const result = await submitTransferOrder();
      // 只有在成功时才关闭弹窗
      if (result !== false) { // submitTransferOrder返回false表示验证失败
        closeModal();
      }
    } catch (error) {
      console.error('确认操作失败:', error);
      // 发生异常时也关闭弹窗
      closeModal();
    }
  } else {
    closeModal();
  }
}

// 提交移库单
async function submitTransferOrder() {
  try {
    loading.value = true;
    // 使用保存的数据快照，避免数据丢失
    const form = confirmData.value || transferForm.value;
    const currentSelectedProduct = confirmData.value?.selectedProduct || selectedProduct.value;
    const currentTransferType = confirmData.value?.transferType || selectedTransferType.value;
    
    console.log('📋 使用的提交数据:', {
      数据来源: confirmData.value ? '快照数据' : '当前表单',
      form: form,
      selectedProduct: currentSelectedProduct,
      transferType: currentTransferType
    });
    
    // ✅ 最终数量验证 - 确保不超过可用库存
    const quantity = parseInt(form.quantity);
    const maxStock = availableStock.value;
    
    console.log(`🔒 提交前最终验证:`, {
      输入数量: quantity,
      可用库存: maxStock,
      商品: currentSelectedProduct?.productName,
      库位: currentSelectedProduct?.locationCode
    });
    
    if (quantity > maxStock) {
      const error = `移库数量 ${quantity} 不能超过可用库存 ${maxStock} 件`;
      console.error('❌', error);
      alert(error);
      return false; // 返回false表示验证失败
    }
    
    // ✅ 首先进行严格的库位存在性验证
    let targetLocationCode = '';
    if (currentTransferType === 'normal' || currentTransferType === 'bad-to-good') {
      targetLocationCode = form.toLocationCode?.trim();
      console.log('🔍 获取目标库位编码:', {
        原始值: form.toLocationCode,
        处理后: targetLocationCode,
        是否为空: !targetLocationCode
      });
      
      // 如果为空，尝试从DOM元素获取（防止Vue绑定失效）
      if (!targetLocationCode) {
        const inputElement = document.querySelector('input[placeholder*="请输入移入库位编码"]');
        if (inputElement && inputElement.value.trim()) {
          targetLocationCode = inputElement.value.trim();
          // 同步回表单数据
          transferForm.value.toLocationCode = targetLocationCode;
          console.log('🔧 从DOM元素获取到库位编码:', targetLocationCode);
        }
      }
    } else if (currentTransferType === 'good-to-bad') {
      targetLocationCode = 'CP-01-01-01-01';
    }
    
    if (targetLocationCode) {
      try {
        console.log(`🔍 提交前验证库位: "${targetLocationCode}"`);
        const locationExists = await transferApi.validateLocationExists(targetLocationCode);
        
        if (!locationExists) {
          alert(`库位编码 "${targetLocationCode}" 在库位管理表中不存在，请检查输入是否正确`);
          // 不清空移入库位数据，让用户修正输入
          locationError.value = `库位编码 "${targetLocationCode}" 不存在`;
          return false; // 返回false表示验证失败
        }
        
        console.log(`✅ 库位验证通过: "${targetLocationCode}"`);
      } catch (error) {
        console.error('❌ 库位验证失败:', error);
        alert(`库位验证失败: ${error.message}\n请检查网络连接或联系管理员`);
        // 不清空移入库位数据，让用户修正输入
        locationError.value = '库位验证失败';
        return false; // 返回false表示验证失败
      }
    }
    
    // ✅ 然后进行完整的数据验证
    console.log('🔍 提交验证前的数据检查:', {
      移库类型: currentTransferType,
      商品名称: currentSelectedProduct.productName,
      数量: quantity,
      表单fromLocation: form.fromLocation,
      表单toLocationCode: form.toLocationCode,
      fromLocation类型: typeof form.fromLocation,
      fromLocation有locationCode: form.fromLocation?.locationCode,
      完整表单数据: form
    });
    
    // ✅ 构建更完整的验证数据
    let validationFromLocation = null;
    
    if (currentTransferType === 'normal' || currentTransferType === 'good-to-bad') {
      // 确保fromLocation有完整的结构
      validationFromLocation = form.fromLocation || {
        id: currentSelectedProduct?.id,
        locationCode: currentSelectedProduct?.locationCode,
        lockedStock: currentSelectedProduct?.lockedStock,
        supplierName: currentSelectedProduct?.supplierName,
        productionDate: currentSelectedProduct?.productionDate
      };
    } else if (currentTransferType === 'bad-to-good') {
      // 残品转良：固定从CP-01-01-01-01
      validationFromLocation = {
        locationCode: 'CP-01-01-01-01'
      };
    }
    
    console.log('🔒 最终验证数据构建:', {
      transferType: currentTransferType,
      productName: currentSelectedProduct.productName,
      quantity: quantity,
      fromLocation: validationFromLocation,
      fromLocationLocationCode: validationFromLocation?.locationCode,
      toLocationCode: form.toLocationCode
    });
    
    const validation = await transferApi.validateTransferDataAsync({
      transferType: currentTransferType,
      productName: currentSelectedProduct.productName,
      quantity: quantity,
      fromLocation: validationFromLocation,
      toLocationCode: form.toLocationCode
    });
    
    if (!validation.isValid) {
      alert('数据验证失败：\n' + validation.errors.join('\n'));
      return false; // 返回false表示验证失败
    }
    
    // 构建移库数据 - 使用验证后的数据
    let fromLocationCode, toLocationCode;
    
    console.log('🔍 移库数据构建前状态:', {
      currentTransferType: currentTransferType,
      formToLocationCode: form.toLocationCode,
      validationFromLocationCode: validationFromLocation?.locationCode,
      selectedProductLocationCode: currentSelectedProduct?.locationCode
    });
    
    if (currentTransferType === 'normal') {
      // ✅ 使用验证过的fromLocation数据，而不是可能为空的selectedProduct
      fromLocationCode = validationFromLocation?.locationCode || currentSelectedProduct.locationCode;
      toLocationCode = form.toLocationCode;
    } else if (currentTransferType === 'good-to-bad') {
      fromLocationCode = validationFromLocation?.locationCode || currentSelectedProduct.locationCode;
      toLocationCode = 'CP-01-01-01-01';
    } else if (currentTransferType === 'bad-to-good') {
      fromLocationCode = 'CP-01-01-01-01';
      toLocationCode = form.toLocationCode;
    }
    
    console.log('🔒 最终移库数据构建:', {
      fromLocationCode: fromLocationCode,
      toLocationCode: toLocationCode,
      transferType: currentTransferType
    });
    
    // ✅ 调试选中商品的完整数据
    console.log('🔍 currentSelectedProduct完整数据:', currentSelectedProduct);
    console.log('🔍 fromLocation数据:', form.fromLocation);
    
    // ✅ 优先从 fromLocation 获取供应商和生产日期数据，因为它包含完整的库存信息
    const supplierName = form.fromLocation?.supplierName || currentSelectedProduct?.supplierName || '';
    const productionDate = form.fromLocation?.productionDate || currentSelectedProduct?.productionDate || '';
    
    console.log('🔍 数据来源检查:', {
      'fromLocation.supplierName': form.fromLocation?.supplierName,
      'currentSelectedProduct.supplierName': currentSelectedProduct?.supplierName,
      '最终supplierName': supplierName,
      'fromLocation.productionDate': form.fromLocation?.productionDate,
      'currentSelectedProduct.productionDate': currentSelectedProduct?.productionDate,
      '最终productionDate': productionDate
    });

    const transferData = {
      transferType: currentTransferType,
      transferNumber: form.transferNumber,
      productName: currentSelectedProduct.productName,
      productBarcode: currentSelectedProduct.barcode || '', // ✅ 添加商品条码
      fromLocationCode: fromLocationCode,
      toLocationCode: toLocationCode,
      quantity: parseInt(form.quantity),
      fromLocationId: currentSelectedProduct?.id,
      supplierName: supplierName,
      productionDate: productionDate
    };
    
    // ✅ 调试：先测试移库单工作表连接和字段映射
    console.log('🔍 测试移库单工作表连接...');
    const connectionTest = await transferApi.testTransferWorksheetConnection();
    console.log('📋 移库单工作表连接测试结果:', connectionTest);
    
    if (!connectionTest.success) {
      alert(`移库单工作表连接失败：${connectionTest.error}\n请检查工作表ID配置`);
      return false; // 返回false表示验证失败
    }
    
    console.log('🔍 验证移库单字段映射...');
    const fieldValidation = await transferApi.validateTransferFieldMapping();
    console.log('📋 移库单字段映射验证结果:', fieldValidation);
    
    if (!fieldValidation.success || !fieldValidation.allFieldsExist) {
      alert(`移库单字段映射有问题：\n有效字段：${fieldValidation.validFields?.join(', ')}\n无效字段：${fieldValidation.invalidFields?.join(', ')}\n\n请检查字段ID配置`);
      return false; // 返回false表示验证失败
    }
    
    console.log('🚀 开始创建移库单...');
    
    // ✅ 添加超时处理
    let result;
    try {
      const createPromise = transferApi.createTransferOrder(transferData);
      const timeoutPromise = new Promise((_, reject) => 
        setTimeout(() => reject(new Error('创建移库单超时(30秒)')), 30000)
      );
      
      result = await Promise.race([createPromise, timeoutPromise]);
      console.log('📬 移库单创建结果:', result);
    } catch (timeoutError) {
      console.error('❌ 创建移库单超时或失败:', timeoutError);
      alert(`创建移库单超时或失败：${timeoutError.message}\n请检查网络连接或稍后重试`);
      return false;
    }
    
    if (result.success) {
      alert('移库单创建成功！');
      currentView.value = 'transfer-types';
      generateTransferNumber();
      resetForm();
      // 重新加载移库单列表
      await loadTransferOrders();
      return true; // 返回true表示成功
    } else {
      console.error('❌ 移库单创建失败详情:', result);
      alert(`创建移库单失败：${result.error}\n\n请检查工作表配置或联系管理员`);
      return false; // 返回false表示失败
    }
    
  } catch (error) {
    console.error('创建移库单失败:', error);
    alert('创建移库单失败，请重试');
    return false; // 返回false表示异常失败
  } finally {
    loading.value = false;
  }
}

// 移库单列表仅用于展示历史记录，不再提供执行功能

// 当前执行的移库单
const currentTransfer = ref(null);

// 获取状态显示文本
function getStatusText(status) {
  return transferApi.getStatusName(status);
}

// 获取状态CSS类
function getStatusClass(status) {
  const classMap = {
    'pending': 'status-pending',
    'executing': 'status-progress',
    'completed': 'status-completed',
    'cancelled': 'status-cancelled',
    'failed': 'status-cancelled'
  };
  return classMap[status] || 'status-unknown';
}

// 关闭弹窗
// 格式化日期时间
function formatDateTime(dateTime) {
  if (!dateTime) return '未知';
  try {
    const date = new Date(dateTime);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit', 
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
  } catch (error) {
    return dateTime;
  }
}

// 格式化日期
function formatDate(dateString) {
  if (!dateString) return '';
  try {
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit'
    });
  } catch (error) {
    return dateString;
  }
}

// 获取库存状态CSS类
function getStockStatusClass(item) {
  const lockedStock = parseInt(item.lockedStock || 0);
  const stockQuantity = parseInt(item.stockQuantity || 0);
  
  if (lockedStock <= 0) {
    return 'status-no-stock';
  } else if (lockedStock < stockQuantity * 0.2) {
    return 'status-low-stock';
  } else if (lockedStock > stockQuantity) {
    return 'status-warning';
  } else {
    return 'status-normal';
  }
}

// 获取库存状态文本
function getStockStatusText(item) {
  const lockedStock = parseInt(item.lockedStock || 0);
  const stockQuantity = parseInt(item.stockQuantity || 0);
  
  if (lockedStock <= 0) {
    return '无库存';
  } else if (lockedStock < stockQuantity * 0.2) {
    return '库存偏低';
  } else if (lockedStock > stockQuantity) {
    return '数据异常';
  } else {
    return '库存正常';
  }
}

function closeModal() {
  showConfirmModal.value = false;
  confirmTitle.value = '';
  confirmMessage.value = '';
  confirmType.value = '';
  confirmData.value = null; // 清理数据快照
  currentTransfer.value = null;
}

// 获取搜索类型显示名称
function getSearchTypeName() {
  switch (currentSearchType.value) {
    case 'location':
      return '库位搜索';
    case 'barcode':
      return '条码搜索';
    case 'combined':
      return '组合搜索';
    default:
      return '';
  }
}

// ✅ 调试方法：测试库位管理表连接
async function testLocationConnection() {
  try {
    console.log('🔍 开始测试库位管理表连接...');
    const result = await transferApi.testLocationManagementConnection();
    
    if (result.success) {
      alert(`库位管理表连接成功！\n找到 ${result.recordCount} 条记录\n请查看控制台了解详细信息`);
    } else {
      alert(`库位管理表连接失败：\n${result.error}\n请检查工作表ID和权限配置`);
    }
  } catch (error) {
    console.error('测试连接失败:', error);
    alert(`测试失败：${error.message}`);
  }
}

// ✅ 调试方法：自动检测库位编码字段ID
async function detectLocationField() {
  try {
    console.log('🔍 开始检测库位编码字段ID...');
    const detectedFieldId = await transferApi.detectLocationFieldId();
    
    if (detectedFieldId) {
      const currentFieldId = transferApi.FIELD_IDS.LOCATION_MANAGEMENT_CODE;
      
      if (detectedFieldId === currentFieldId) {
        alert(`✅ 字段ID验证通过！\n当前配置: ${currentFieldId}\n检测结果: ${detectedFieldId}\n字段ID配置正确`);
      } else {
        alert(`⚠️ 字段ID可能需要更新！\n当前配置: ${currentFieldId}\n检测建议: ${detectedFieldId}\n\n请检查控制台日志了解详情`);
      }
    } else {
      alert(`❌ 无法自动检测字段ID\n请手动检查库位管理表的数据结构\n查看控制台了解详细信息`);
    }
  } catch (error) {
    console.error('字段ID检测失败:', error);
    alert(`检测失败：${error.message}`);
  }
}

// ✅ 调试方法：测试库位验证功能（精准匹配）
async function testLocationValidation() {
  const testLocationCode = prompt(
    '请输入要测试的库位编码:\n注意：使用精准匹配，区分大小写', 
    'A01-01-01-01'
  );
  
  if (!testLocationCode) {
    return;
  }
  
  try {
    console.log(`🔍 精准匹配测试库位验证: "${testLocationCode}"`);
    console.log(`输入详情:`, {
      原始输入: testLocationCode,
      处理后: testLocationCode.trim(),
      长度: testLocationCode.trim().length,
      字符: Array.from(testLocationCode.trim())
    });
    
    const exists = await transferApi.validateLocationExists(testLocationCode);
    
    if (exists) {
      alert(`✅ 库位编码 "${testLocationCode}" 精准匹配验证通过！\n该库位存在于库位管理表中\n\n请查看控制台了解匹配详情`);
    } else {
      alert(`❌ 库位编码 "${testLocationCode}" 精准匹配验证失败！\n该库位不存在于库位管理表中\n\n注意：\n- 检查大小写是否正确\n- 检查是否有多余的空格\n- 查看控制台了解详细匹配过程`);
    }
  } catch (error) {
    console.error('库位验证测试失败:', error);
    alert(`验证测试失败：${error.message}\n请查看控制台了解详细信息`);
  }
}

// ✅ 调试方法：测试移库单工作表连接
async function testTransferWorksheetConnection() {
  try {
    console.log('🔍 开始测试移库单工作表连接...');
    const result = await transferApi.testTransferWorksheetConnection();
    
    if (result.success) {
      alert(`移库单工作表连接成功！\n找到 ${result.recordCount} 条记录\n请查看控制台了解详细信息`);
    } else {
      alert(`移库单工作表连接失败：\n${result.error}\n请检查工作表ID和权限配置`);
    }
  } catch (error) {
    console.error('测试连接失败:', error);
    alert(`测试失败：${error.message}`);
  }
}

// ✅ 调试方法：验证移库单字段映射
async function validateTransferFieldMapping() {
  try {
    console.log('🔍 开始验证移库单字段映射...');
    const result = await transferApi.validateTransferFieldMapping();
    
    if (result.success) {
      const status = result.allFieldsExist ? '✅' : '❌';
      alert(`${status} 字段映射验证结果：\n${result.message}\n\n详细信息请查看控制台`);
    } else {
      alert(`❌ 验证失败：\n${result.error || result.message}\n请查看控制台了解详细信息`);
    }
  } catch (error) {
    console.error('字段映射验证失败:', error);
    alert(`验证失败：${error.message}`);
  }
}

// ✅ 调试方法：测试字段映射功能
async function testFieldMapping() {
  try {
    console.log('🔍 开始测试字段映射功能...');
    
    // 模拟移库单数据
    const testData = {
      productName: 'test2 润唇膏 10个 200ml/管-复制 10个 200ml/管',
      fromLocationCode: 'AA-01-01-01-01',
      toLocationCode: 'BB-01-01-01-01', 
      quantity: 5,
      transferType: 'normal'
    };
    
    const additionalFields = await transferApi.buildAdditionalTransferFields(testData);
    
    console.log('🎯 字段映射测试结果:', {
      测试数据: testData,
      映射字段: additionalFields
    });
    
    alert(`字段映射测试完成！\n映射了 ${additionalFields.length} 个字段\n请查看控制台了解详细信息`);
    
  } catch (error) {
    console.error('字段映射测试失败:', error);
    alert(`测试失败：${error.message}`);
  }
}

// 将调试函数挂载到window对象，方便控制台调用
function exposeDebugFunctions() {
  if (typeof window !== 'undefined') {
    window.checkRuntimeConfig = checkRuntimeConfig;
    window.testApiInit = testApiInit;
    window.testLocationConnection = testLocationConnection;
    window.testLocationValidation = testLocationValidation;
    window.detectLocationField = detectLocationField;
    window.testTransferWorksheetConnection = testTransferWorksheetConnection;
    window.validateTransferFieldMapping = validateTransferFieldMapping;
    window.testFieldMapping = testFieldMapping;
    
    console.log('🔧 调试函数已挂载到window对象，可以使用:');
    console.log('- checkRuntimeConfig() - 检查运行时配置');
    console.log('- testApiInit() - 测试API初始化');
    console.log('- testLocationConnection() - 测试库位管理表连接');
    console.log('- testLocationValidation() - 测试库位验证');
  }
}

// ✅ 新增调试方法：检查运行时配置
function checkRuntimeConfig() {
  console.log('🔧 开始检查运行时配置...');
  
  // 检查各种可能的配置源
  const configSources = {
    'window.mdye.env.config': (typeof window !== 'undefined') ? window.mdye?.env?.config : undefined,
    'window.env.config': (typeof window !== 'undefined') ? window.env?.config : undefined,
    'window.mdye.config': (typeof window !== 'undefined') ? window.mdye?.config : undefined,
    'window.config': (typeof window !== 'undefined') ? window.config : undefined
  };
  
  // 检查父窗口配置
  try {
    if (typeof window !== 'undefined' && window.parent && window.parent !== window) {
      configSources['parent.mdye.env.config'] = window.parent.mdye?.env?.config;
      configSources['parent.env.config'] = window.parent.env?.config;
      configSources['parent.mdye.config'] = window.parent.mdye?.config;
      configSources['parent.config'] = window.parent.config;
    }
  } catch(e) {}
  
  // 检查顶层窗口配置
  try {
    if (typeof window !== 'undefined' && window.top && window.top !== window) {
      configSources['top.mdye.env.config'] = window.top.mdye?.env?.config;
      configSources['top.env.config'] = window.top.env?.config;
      configSources['top.mdye.config'] = window.top.mdye?.config;
      configSources['top.config'] = window.top.config;
    }
  } catch(e) {}
  
  console.log('📋 配置源检查结果:', Object.fromEntries(
    Object.entries(configSources).map(([key, value]) => [
      key, 
      {
        存在: !!value,
        类型: typeof value,
        是否为数组: Array.isArray(value),
        键数量: value && typeof value === 'object' ? Object.keys(value).length : 0,
        样例键: value && typeof value === 'object' ? Object.keys(value).slice(0, 5) : []
      }
    ])
  ));
  
  // 详细显示有效配置
  Object.entries(configSources).forEach(([sourceName, config]) => {
    if (config && typeof config === 'object') {
      console.log(`\n🎯 ${sourceName} 详细内容:`, config);
      
      if (Array.isArray(config)) {
        console.log(`  📦 数组格式，包含 ${config.length} 项:`);
        config.forEach((item, index) => {
          if (item && typeof item === 'object') {
            console.log(`    项目 ${index}:`, {
              controlName: item.controlName,
              fieldId: item.fieldId,
              value: item.value,
              default: item.default
            });
          }
        });
      } else {
        console.log(`  📦 对象格式，包含键:`, Object.keys(config));
        Object.entries(config).forEach(([key, value]) => {
          console.log(`    ${key}: ${value}`);
        });
      }
    }
  });
  
  // 测试关键配置获取
  console.log('\n🔍 测试关键配置获取:');
  const keyConfigs = ['AppKey', 'Sign', 'SecretKey', 'LOCATION_STOCK', 'TRANSFER_ORDERS', 'LOCATION_MANAGEMENT', 'webhookUrl'];
  
  keyConfigs.forEach(key => {
    try {
      const value = transferApi.getEnvValue ? transferApi.getEnvValue(key) : '方法不存在';
      console.log(`  ${key}: "${value}" (${typeof value})`);
    } catch (error) {
      console.error(`  ${key}: 获取失败 - ${error.message}`);
    }
  });
  
  alert('配置检查完成！请查看控制台了解详细信息');
}

// ✅ 新增调试方法：测试API初始化
async function testApiInit() {
  try {
    console.log('🔧 测试API初始化...');
    
    // 检查API环境
    console.log('🔍 API环境检查:', {
      'window.api存在': !!(typeof window !== 'undefined' && window.api),
      'window.api.call存在': !!(typeof window !== 'undefined' && window.api && window.api.call),
      'window.api.worksheet存在': !!(typeof window !== 'undefined' && window.api && window.api.worksheet),
      'mdye.api存在': !!(window.mdye && window.mdye.api),
      '导入的api存在': !!transferApi.callApi
    });
    
    // 重新初始化
    transferApi.init();
    
    console.log('📋 初始化后的配置状态:', {
      API_CONFIG: {
        baseURL: transferApi.API_CONFIG?.baseURL,
        appKey: transferApi.API_CONFIG?.appKey ? '已配置' : '未配置',
        sign: transferApi.API_CONFIG?.sign ? '已配置' : '未配置',
        secretKey: transferApi.API_CONFIG?.secretKey ? '已配置' : '未配置'
      },
      WORKSHEET_IDS: {
        LOCATION_STOCK: transferApi.WORKSHEET_IDS?.LOCATION_STOCK || '未配置',
        TRANSFER_ORDERS: transferApi.WORKSHEET_IDS?.TRANSFER_ORDERS || '未配置', 
        LOCATION_MANAGEMENT: transferApi.WORKSHEET_IDS?.LOCATION_MANAGEMENT || '未配置'
      },
      webhookUrl: transferApi.webhookUrl ? '已配置' : '未配置'
    });
    
    // 测试基本API调用
    console.log('🔍 测试基本API连接...');
    
    // 先测试简单的API调用
    if (transferApi.WORKSHEET_IDS.LOCATION_STOCK) {
      console.log('📡 尝试调用 getFilterRows...');
      const testResult = await transferApi.callApi('getFilterRows', {
        worksheetId: transferApi.WORKSHEET_IDS.LOCATION_STOCK,
        pageSize: 1
      });
      
      console.log('✅ API调用测试成功:', {
        响应类型: typeof testResult,
        有数据: !!(testResult && testResult.data),
        数据长度: testResult?.data?.length || 0
      });
      
      alert(`API初始化测试完成！\nAPI调用成功，工作表有数据\n请查看控制台了解详细信息`);
    } else {
      alert(`配置检查失败：LOCATION_STOCK未配置\n请检查明道云插件配置`);
    }
    
  } catch (error) {
    console.error('❌ API初始化测试失败:', error);
    console.error('错误详情:', {
      message: error.message,
      stack: error.stack,
      name: error.name
    });
    
    alert(`API初始化测试失败：\n${error.message}\n\n请检查:\n1. 明道云配置是否正确\n2. 网络连接是否正常\n3. 工作表权限是否足够\n4. 查看控制台了解详细错误`);
  }
}
</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.wms-app {
  min-height: 100vh;
  background-color: #f5f5f5;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.header {
  background-color: #f8b300;
  padding: 1rem;
  color: white;
  display: flex;
  align-items: center;
  gap: 1rem;
}

.header h1, .header h2 {
  margin: 0;
  font-weight: 600;
}

.back-btn {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
  padding: 0.5rem 1rem;
  border-radius: 6px;
  cursor: pointer;
  font-size: 0.9rem;
  transition: background-color 0.2s;
}

.back-btn:hover {
  background: rgba(255, 255, 255, 0.3);
}

.add-btn {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
  padding: 0.5rem 1rem;
  border-radius: 6px;
  cursor: pointer;
  font-size: 0.9rem;
  transition: background-color 0.2s;
  margin-left: auto;
}

.add-btn:hover {
  background: rgba(255, 255, 255, 0.3);
}


/* 移库类型选择页面 */
.transfer-types {
  min-height: 100vh;
}

.transfer-type-grid {
  padding: 2rem;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 1.5rem;
  max-width: 1400px;
  margin: 0 auto;
}

.transfer-type-card {
  background: white;
  border-radius: 12px;
  padding: 2rem;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: all 0.3s ease;
  border-left: 4px solid #f8b300;
  text-align: center;
}

.transfer-type-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 25px rgba(248, 179, 0, 0.2);
}

.type-icon {
  font-size: 3rem;
  margin-bottom: 1rem;
}

.type-name {
  font-size: 1.5rem;
  font-weight: 600;
  color: #333;
  margin-bottom: 0.5rem;
}

.type-desc {
  color: #666;
  font-size: 1rem;
}

/* 移库单创建页面 */
.create-transfer {
  min-height: 100vh;
}

.transfer-form {
  padding: 1rem;
  max-width: 600px;
  margin: 0 auto;
}

.form-section {
  background: white;
  border-radius: 8px;
  padding: 1.5rem;
  margin-bottom: 1rem;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.section-title {
  font-size: 1.1rem;
  font-weight: 600;
  color: #333;
  margin-bottom: 1rem;
  border-bottom: 2px solid #f8b300;
  padding-bottom: 0.5rem;
}

.form-group {
  margin-bottom: 1rem;
}

.form-group:last-child {
  margin-bottom: 0;
}

.form-group label {
  display: block;
  font-weight: 600;
  color: #333;
  margin-bottom: 0.5rem;
  font-size: 0.9rem;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 0.75rem;
  border: 2px solid #ddd;
  border-radius: 6px;
  font-size: 1rem;
  transition: border-color 0.2s;
}

.form-group input:focus,
.form-group select:focus {
  outline: none;
  border-color: #f8b300;
}

.form-group input:disabled {
  background-color: #f5f5f5;
  color: #666;
  cursor: not-allowed;
}

.fixed-location {
  background-color: #e8f5e8 !important;
  border-color: #28a745 !important;
  color: #155724 !important;
  font-weight: 600;
}

.auto-filled {
  background-color: #f8f9fa !important;
  border-color: #6c757d !important;
  color: #495057 !important;
}

/* 搜索相关样式 */

.search-input-container {
  display: flex;
  gap: 0.5rem;
  align-items: center;
}

.search-input {
  flex: 1;
  padding: 0.75rem;
  border: 2px solid #ddd;
  border-radius: 6px;
  font-size: 1rem;
}

.search-input:focus {
  outline: none;
  border-color: #f8b300;
}

.search-btn {
  padding: 0.75rem 1.5rem;
  background: #f8b300;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 600;
  white-space: nowrap;
  transition: background 0.2s;
}

.search-btn:hover:not(:disabled) {
  background: #e6a200;
}

.search-btn:disabled {
  background: #6c757d;
  cursor: not-allowed;
}

/* 搜索结果样式 */
.search-results {
  margin-top: 1rem;
  max-height: 400px;
  overflow-y: auto;
  border: 1px solid #ddd;
  border-radius: 6px;
}

.results-header {
  padding: 0.75rem 1rem;
  background: #f8f9fa;
  border-bottom: 1px solid #ddd;
  font-weight: 600;
  color: #495057;
  font-size: 0.9rem;
}

.results-list {
  max-height: 300px;
  overflow-y: auto;
}

.result-item {
  display: flex;
  align-items: center;
  padding: 1rem;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background 0.2s;
}

.result-item:hover {
  background: #f8f9fa;
}

.result-item.selected {
  background: #e6f3ff;
  border-left: 4px solid #f8b300;
}

.result-item:last-child {
  border-bottom: none;
}

.result-main {
  flex: 1;
}

.product-name {
  font-weight: 600;
  color: #333;
  margin-bottom: 0.75rem;
  font-size: 1.2rem; /* 扩大显示 */
  line-height: 1.3;
}

/* 产品信息网格布局 */
.product-info-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 0.5rem 1rem;
  margin-bottom: 0.5rem;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.info-label {
  font-size: 0.9rem;
  color: #666;
  font-weight: 500;
  min-width: 50px;
  flex-shrink: 0;
}

.info-value {
  font-size: 0.95rem;
  font-weight: 500;
  flex: 1;
}

/* 特定信息的颜色 */
.info-value.barcode {
  color: #007bff;
}

.info-value.location {
  color: #28a745;
}

.info-value.stock {
  color: #fd7e14;
  font-weight: 600;
}

.info-value.supplier {
  color: #6c757d;
}

.info-value.production-date {
  color: #6c757d;
  font-size: 0.9rem;
}

.info-value.total-stock {
  color: #6c757d;
  font-size: 0.9rem;
}

.select-indicator {
  width: 30px;
  text-align: center;
  font-size: 1.2rem;
  color: #28a745;
  font-weight: bold;
}

/* 已选择商品样式 */
.selected-product {
  margin-top: 1rem;
  padding: 1rem;
  background: #e6f3ff;
  border: 2px solid #f8b300;
  border-radius: 6px;
}

.selected-header {
  font-weight: 600;
  color: #333;
  margin-bottom: 0.5rem;
  font-size: 0.9rem;
}

.selected-name {
  font-weight: 600;
  color: #333;
  margin-bottom: 0.5rem;
  font-size: 1.1rem;
}

.selected-details {
  display: flex;
  gap: 1rem;
  font-size: 0.9rem;
  color: #666;
  flex-wrap: wrap;
}

.selected-details span {
  white-space: nowrap;
}

/* 搜索类型提示样式 */
.search-type-hint {
  margin-top: 0.5rem;
  padding: 0.5rem;
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 4px;
  font-size: 0.85rem;
  color: #6c757d;
  text-align: center;
}

/* 新增：组合搜索按钮样式 */
.combined-search-btn {
  width: 100%;
  padding: 0.75rem 1.5rem;
  background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 600;
  font-size: 1rem;
  transition: all 0.2s ease;
  margin-top: 0.5rem;
}

.combined-search-btn:hover {
  background: linear-gradient(135deg, #218838 0%, #1e9e8a 100%);
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(40, 167, 69, 0.3);
}

.combined-search-btn:disabled {
  background: #6c757d;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

/* 搜索按钮样式 */
.smart-search-btn {
  width: 100%;
  max-width: none;
  margin: 0;
  height: 44px; /* 等比缩小高度 */
  padding: 0.6rem 1rem; /* 减少内边距 */
  background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-weight: 600;
  font-size: 1rem; /* 缩小字体 */
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  box-shadow: 0 2px 4px rgba(40, 167, 69, 0.2);
}

.smart-search-btn:hover:not(:disabled) {
  background: linear-gradient(135deg, #218838 0%, #1e9e8a 100%);
  transform: translateY(-2px);
  box-shadow: 0 6px 12px rgba(40, 167, 69, 0.3);
}

.smart-search-btn:disabled {
  background: #6c757d;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

/* 搜索按钮内容样式 */
.search-icon {
  font-size: 1.2rem;
}

.search-text {
  font-weight: 600;
}

/* 搜索预览样式 */
.search-preview {
  margin-top: 0.5rem;
  padding: 0.75rem;
  background: linear-gradient(135deg, #e3f2fd 0%, #f3e5f5 100%);
  border: 1px solid #2196f3;
  border-radius: 6px;
  font-size: 0.9rem;
  color: #1976d2;
  text-align: center;
  font-style: italic;
}

/* 新增：搜索类型标记样式 */
.search-type-badge {
  display: inline-block;
  margin-left: 0.5rem;
  padding: 0.2rem 0.5rem;
  background: #f8b300;
  color: white;
  border-radius: 12px;
  font-size: 0.75rem;
  font-weight: 500;
}

/* 窄搜索框样式 - 适配移动端 */
.mobile-narrow {
  width: 100% !important;
  max-width: none !important;
  margin: 0;
  font-size: 0.9rem;
  padding: 0.5rem 0.75rem; /* 减少垂直高度 */
  height: 40px; /* 固定高度 */
}

/* 紧凑布局样式 */
.compact-section {
  padding: 1rem !important;
  margin-bottom: 0.75rem !important;
}

/* 内联输入样式 */
.inline-input {
  display: flex !important;
  align-items: center !important;
  margin-bottom: 0.75rem !important;
}

.inline-label {
  width: 60px !important;
  min-width: 60px !important;
  margin-right: 0.75rem !important;
  margin-bottom: 0 !important;
  font-size: 0.9rem !important;
  font-weight: 600 !important;
  color: #333 !important;
  text-align: right !important;
}

.inline-input-field {
  flex: 1 !important;
  margin-left: 0 !important;
}

/* 内联显示样式 */
.inline-display {
  color: #28a745;
  font-weight: 600;
  font-size: 1rem;
  display: flex;
  align-items: center;
  height: 40px;
  padding: 0 0.5rem;
}

/* 去移库按钮样式 */
.go-transfer-btn {
  width: 80% !important;
  max-width: 80% !important;
  background: #28a745 !important;
  margin: 0 auto;
  display: block;
}

.go-transfer-btn:hover:not(:disabled) {
  background: #218838 !important;
}

.go-transfer-btn:disabled {
  background: #6c757d !important;
}

/* 库存状态样式 */
.stock-status {
  margin-top: 0.5rem;
}

.status-indicator {
  display: inline-block;
  padding: 0.2rem 0.5rem;
  border-radius: 12px;
  font-size: 0.75rem;
  font-weight: 500;
  text-transform: uppercase;
}

.status-normal {
  background-color: #d4edda;
  color: #155724;
  border: 1px solid #c3e6cb;
}

.status-low-stock {
  background-color: #fff3cd;
  color: #856404;
  border: 1px solid #ffeaa7;
}

.status-warning {
  background-color: #f8d7da;
  color: #721c24;
  border: 1px solid #f5c6cb;
}

.status-no-stock {
  background-color: #e2e3e5;
  color: #383d41;
  border: 1px solid #d6d8db;
}

.total-stock {
  color: #6c757d !important;
  font-size: 0.85rem;
}

.production-date {
  color: #6c757d;
  font-size: 0.85rem;
}

/* ✅ 新增：输入提示样式 */
.input-hint {
  margin-top: 0.5rem;
  padding: 0.5rem;
  background: #e3f2fd;
  border: 1px solid #2196f3;
  border-radius: 4px;
  font-size: 0.85rem;
  color: #1976d2;
  text-align: center;
}

.stock-info {
  color: #28a745;
  font-weight: 600;
  font-size: 1rem;
}

.form-group input.error {
  border-color: #dc3545;
  box-shadow: 0 0 0 0.2rem rgba(220, 53, 69, 0.25);
}

.error-message {
  margin-top: 0.5rem;
  color: #dc3545;
  font-size: 0.85rem;
  font-weight: 500;
  background: #f8d7da;
  border: 1px solid #f5c6cb;
  border-radius: 4px;
  padding: 0.5rem;
}

.form-actions {
  text-align: center;
  margin-top: 2rem;
}

.submit-btn {
  background: #28a745;
  color: white;
  border: none;
  padding: 1rem 2rem;
  border-radius: 8px;
  font-size: 1.1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s ease;
  min-width: 200px;
}

.submit-btn:hover:not(:disabled) {
  background: #218838;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(40, 167, 69, 0.3);
}

.submit-btn:disabled {
  background: #6c757d;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

/* 移库单列表页面 */
.transfer-list {
  min-height: 100vh;
}

.transfer-items {
  padding: 1rem;
}

.transfer-item {
  background: white;
  border-radius: 8px;
  padding: 1.5rem;
  margin-bottom: 1rem;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  width: 100%;
}

.transfer-info {
  flex: 1;
}

.transfer-number {
  font-size: 1.2rem;
  font-weight: 600;
  color: #333;
  margin-bottom: 0.75rem;
}

.transfer-meta {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 0.5rem;
  margin-bottom: 0.75rem;
}

.meta-item {
  display: flex;
  align-items: center;
  font-size: 0.9rem;
}

.meta-label {
  color: #666;
  font-weight: 500;
  margin-right: 0.5rem;
  min-width: 60px;
}

.meta-value {
  color: #333;
  font-weight: 400;
}

.meta-value.status {
  padding: 0.2rem 0.5rem;
  border-radius: 12px;
  font-size: 0.8rem;
  font-weight: 500;
}

.status-pending {
  background: #fff3cd;
  color: #856404;
}

.status-progress {
  background: #d1ecf1;
  color: #0c5460;
}

.status-completed {
  background: #d4edda;
  color: #155724;
}

.status-cancelled {
  background: #f8d7da;
  color: #721c24;
}

.status-unknown {
  background: #e2e3e5;
  color: #383d41;
}

/* 空状态样式 */
.empty-state {
  text-align: center;
  padding: 3rem 1rem;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.empty-icon {
  font-size: 4rem;
  margin-bottom: 1rem;
}

.empty-text {
  font-size: 1.2rem;
  color: #666;
  margin-bottom: 2rem;
}

.create-btn {
  background: #f8b300;
  color: white;
  border: none;
  padding: 1rem 2rem;
  border-radius: 8px;
  cursor: pointer;
  font-size: 1rem;
  font-weight: 600;
  transition: all 0.2s ease;
}

.create-btn:hover {
  background: #e6a200;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(248, 179, 0, 0.3);
}

.location-info {
  display: flex;
  gap: 1rem;
  color: #666;
  font-size: 0.9rem;
}

/* 移库单列表仅展示历史记录，移除执行按钮样式 */

/* 确认弹窗 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 12px;
  padding: 2rem;
  max-width: 400px;
  width: 90%;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
}

.modal-content h3 {
  color: #333;
  margin-bottom: 1rem;
  font-size: 1.3rem;
}

.modal-content p {
  color: #666;
  margin-bottom: 2rem;
  line-height: 1.5;
  white-space: pre-line;
}

.modal-actions {
  display: flex;
  gap: 1rem;
  justify-content: flex-end;
}

.cancel-btn, .confirm-btn {
  padding: 0.75rem 1.5rem;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.2s;
}

.cancel-btn {
  background: #f8f9fa;
  color: #333;
  border: 1px solid #ddd;
}

.cancel-btn:hover {
  background: #e9ecef;
}

.confirm-btn {
  background: #f8b300;
  color: white;
}

.confirm-btn:hover {
  background: #e6a200;
}

@media (max-width: 768px) {
  .transfer-type-grid {
    grid-template-columns: repeat(2, 1fr);
    padding: 1rem;
    gap: 1rem;
  }
  
  /* 移动端表单优化 */
  .form-section {
    padding: 1rem;
    margin-bottom: 0.75rem;
  }
  
  .compact-section {
    padding: 0.75rem !important;
    margin-bottom: 0.5rem !important;
  }
  
  .form-group {
    margin-bottom: 0.75rem;
  }
  
  .inline-input {
    margin-bottom: 0.5rem !important;
  }
  
  .inline-label {
    width: 50px !important;
    min-width: 50px !important;
    margin-right: 0.5rem !important;
    font-size: 0.85rem !important;
  }
  
  .form-group input {
    padding: 0.8rem;
    font-size: 16px; /* 防止iOS缩放 */
  }
  
  /* 移动端搜索框窄化 */
  .mobile-narrow {
    width: 100% !important;
    max-width: none !important;
    height: 38px !important; /* 移动端更矮 */
    padding: 0.45rem 0.7rem !important;
  }
  
  /* 移动端搜索按钮 */
  .smart-search-btn {
    width: 100% !important;
    max-width: none !important;
    height: 42px !important; /* 移动端等比缩小 */
    padding: 0.55rem 1rem !important;
    font-size: 0.95rem !important;
  }
}

@media (max-width: 480px) {
  .transfer-type-grid {
    grid-template-columns: 1fr;
    padding: 1rem;
  }
  
  .transfer-form {
    padding: 0.5rem;
  }
  
  .compact-section {
    padding: 0.5rem !important;
    margin-bottom: 0.5rem !important;
  }
  
  .inline-input {
    margin-bottom: 0.4rem !important;
  }
  
  .inline-label {
    width: 45px !important;
    min-width: 45px !important;
    margin-right: 0.4rem !important;
    font-size: 0.8rem !important;
  }
  
  .transfer-type-card {
    padding: 1.5rem;
  }
  
  .type-icon {
    font-size: 2.5rem;
  }
  
  .type-name {
    font-size: 1.2rem;
  }
  
  .type-desc {
    font-size: 0.9rem;
  }
  
  .transfer-item {
    padding: 1rem;
  }
  
  .transfer-meta {
    grid-template-columns: 1fr;
    gap: 0.25rem;
  }
  
  
  .empty-state {
    margin: 1rem 0.5rem;
    padding: 2rem 1rem;
  }
  
  .empty-icon {
    font-size: 3rem;
  }
  
  .empty-text {
    font-size: 1rem;
  }
  
  .create-btn {
    width: 100%;
    padding: 1rem;
  }
  
  /* 移动端搜索样式调整 */
  .search-input-container {
    flex-direction: column;
    gap: 0.75rem;
  }
  
  .search-btn {
    width: 100%;
    padding: 0.6rem;
    height: 40px;
  }
  
  .combined-search-btn {
    padding: 0.6rem;
    font-size: 1rem;
    height: 40px;
  }
  
  .smart-search-btn {
    padding: 0.6rem 1rem !important;
    font-size: 0.9rem !important;
    height: 40px !important;
  }
  
  .search-preview {
    padding: 1rem;
    font-size: 1rem;
  }
  
  .product-details {
    flex-direction: column;
    gap: 0.25rem;
  }
  
  /* 移动端产品信息网格优化 */
  .product-info-grid {
    grid-template-columns: 1fr !important;
    gap: 0.4rem !important;
  }
  
  .info-item {
    gap: 0.4rem !important;
  }
  
  .info-label {
    min-width: 60px !important;
    font-size: 0.85rem !important;
  }
  
  .info-value {
    font-size: 0.9rem !important;
  }
  
  .selected-details {
    flex-direction: column;
    gap: 0.25rem;
  }
  
  .search-results {
    max-height: 300px;
  }
  
  .results-list {
    max-height: 250px;
  }
}
</style>